[SOLVED]Django - Passing variables to template based on db

Posted by George 'Griffin on Stack Overflow See other posts from Stack Overflow or by George 'Griffin
Published on 2011-01-03T23:55:01Z Indexed on 2011/01/04 22:53 UTC
Read the original article Hit count: 155

Filed under:
|
|

I am trying to add a feature to my app that would allow me to enable/disable the "Call Me" button based on whether or not I am at [home|the office]. I created a model in the database called setting, it looks like this:

class setting(models.Model): 
    key = models.CharField(max_length=200)
    value = models.CharField(max_length=200)

Pretty simple. There is currently one row, available, the value of it is the string True. I want to be able to transparently pass variables to the templates like this:

{% if available %}
   <!-- Display button -->
{% else %}
   <!-- Display grayed out button -->
{% endif %}

Now, I could add logic to every view that would check the database, and pass the variable to the template, but I am trying to stay DRY.

What is the best way to do this?

UPDATE I created a context processor, and added it's path to the TEMPLATE_CONTEXT_PROCESSORS, but it is not being passed to the template

def available(request):
available = Setting.objects.get(key="available")
if open.value == "True":
    return {"available":True}
else:
    return {}

UPDATE TWO If you are using the shortcut render_to_response, you need to pass an instance of RequestContext to the function.

from the django documentation:

If you're using Django's render_to_response() shortcut to populate a template with the contents of a dictionary, your template will be passed a Context instance by default (not a RequestContext). To use a RequestContext in your template rendering, pass an optional third argument to render_to_response(): a RequestContext instance. Your code might look like this:

def some_view(request):
     # ...
     return render_to_response('my_template.html',
                               my_data_dictionary,
                               context_instance=RequestContext(request))

Many thanks for all the help!

© Stack Overflow or respective owner

Related posts about python

Related posts about django